#include <cstdio>
#include <cstdlib>

#include <getopt.h>

#include "mtf"
#include "mtfAlt"

const char USAGE[] = "\
 [OPTION]...\n\
MTFize or de-MTFize standard input to standard output.\n\n\
  -z                       MTFize (default)\n\
  -x                       de-MTFize\n\
  -v                       verbose, print per-char diagnostics to stderr\n\
  -q                       quiet, do not print diagnostics (default)\n\
  -h                       display this help and quit\
";

int main (int argc, char *argv[]) {
	bool
		compressing = true,
		alt = false,
		verbose = false,
		help = false,
		fail = false;
	unsigned in;
	uchar out;
	mxf *processor = nullptr;

	for (char c; (c = getopt(argc, argv, "zxavqh")) != -1;) {
		switch (c) {
		case 'z': compressing = true; break;
		case 'x': compressing = false; break;
		case 'a': alt = true; break;
		case 'v': verbose = true; break;
		case 'q': verbose = false; break;
		case 'h': help = true; break;
		default: fail = true; break;
		}
	}
	if (help or fail) {
		printf("Usage: %s%s\n", argv[0], USAGE);
		exit(fail? EXIT_FAILURE : EXIT_SUCCESS);
	}

	processor =
		compressing
			?(alt
				?(mxf*)(new mtfAlt)
				:(mxf*)(new mtf))
			:(alt
				?(mxf*)(new mffAlt)
				:(mxf*)(new mff));

	while((in = getchar()) != EOF) {
		out = (*processor)(in);
		putchar(out);
		if(verbose) {
			fprintf(stderr, "'%1$c' (x%1$.2X) => '%2$c' (x%2$.2X / %2$d)\n", in, out);
		}
	}

	delete processor;
	exit(EXIT_SUCCESS);
}

